<template>
  <BasicDrawer
    v-bind="$attrs"
    width="50%"
    @register="register"
    showFooter
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { BasicForm, useForm } from '@/components/Form/index';
import { formSchema } from './data';
import { useMessage } from '@/hooks/web/useMessage';
import { getMenuList } from '@/api/sys/system';
import { edit, add } from '@/api/sys/dev/codeGenManager';
import { cacheApi } from '@/api/sys/common';
import { upperFirst, camelCase } from 'lodash-es';
import { getTableList } from '@/api/sys/system';

export default defineComponent({
  name: 'CodeConfigModal',
  components: { BasicForm, BasicDrawer },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    let isUpdate = ref(true);
    const columnsRef = ref();
    const { createMessage } = useMessage();
    const [
      registerForm,
      { resetFields, setFieldsValue, validate, updateSchema },
    ] = useForm({
      labelWidth: 120,
      schemas: formSchema,
      baseColProps: { span: 12 },
      showActionButtonGroup: false,
    });
    const codeGenId = ref();
    const loadColumnsConfig = (genId) => {
      codeGenId.value = genId;
      setTimeout(() => {
        columnsRef.value.reload();
      });
    };
    const setDefaultProperties = (
      formModel: Recordable,
      record: Recordable
    ) => {
      if (!record) return;
      setTimeout(() => {
        formModel.tableComment = record.tableComment;
        formModel.className = upperFirst(camelCase(formModel.tableName));
        formModel.packageName = 'com.hls.ams';
      });
    };
    const [register, { setDrawerProps, closeDrawer }] = useDrawerInner(
      async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        // 更新componentProps为函数的schema时 要写全schema
        updateSchema([
          {
            field: 'dataSource',
            componentProps: ({ formModel }) => {
              return {
                showSearch: true,
                api: cacheApi,
                params: { keyCode: 'datasource', keyType: 'other' },
                onChange: () => {
                  formModel.tableName = undefined;
                },
                disabled: isUpdate.value,
              };
            },
          },
          {
            field: 'tableName',
            componentProps: ({ formModel }) => {
              return {
                showSearch: true,
                api: getTableList,
                valueField: 'tableName',
                labelField: 'tableName',
                params: { dataSourceCode: formModel.dataSource },
                onChange: (e, record) => {
                  console.log('change');
                  setDefaultProperties(formModel, record);
                },
                disabled: isUpdate.value,
              };
            },
          },
        ]);

        if (unref(isUpdate)) {
          const { actionType } = data.record;
          setFieldsValue({
            ...data.record,
            actionType: actionType ? actionType.split(',') : [],
          });
        }

        const treeData = await getMenuList();
        updateSchema({
          field: 'menuPid',
          componentProps: {
            treeData,
          },
        });
      }
    );

    const getTitle = computed(() =>
      !unref(isUpdate) ? '新增配置' : '编辑配置'
    );

    async function handleSubmit() {
      try {
        const values = await validate();
        setDrawerProps({ confirmLoading: true });
        const { actionType } = values;
        const data = {
          ...values,
          actionType: actionType ? actionType.toString() : '',
        };
        if (values.id) {
          await edit(data);
          createMessage.success('修改成功');
          closeDrawer();
        } else {
          await add(data);
          createMessage.success('保存成功');
          closeDrawer();
        }

        emit('success');
      } finally {
        setDrawerProps({ confirmLoading: false });
      }
    }

    return {
      isUpdate,
      codeGenId,
      columnsRef,
      register,
      registerForm,
      getTitle,
      handleSubmit,
    };
  },
});
</script>
